package com.wsjc.app.push.core;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Sets;
import com.wsjc.app.push.App;
import com.wsjc.app.push.socket.SystemWebSocketHandler;
import com.wsjc.common.core.constants.CommonConst;
import com.wsjc.common.core.entity.ApiCommonResultVo;
import com.wsjc.manager.entity.WjArea;
import com.wsjc.manager.entity.WjCity;
import com.wsjc.manager.entity.WjDataLog;
import com.wsjc.manager.entity.WjProvince;
import com.wsjc.manager.entity.WjUser;
import com.wsjc.manager.entity.vo.push.SocketRespVo;
import com.wsjc.manager.service.routine.datalog.WjDataLogService;
import com.wsjc.manager.service.routine.push.WjPushService;
import com.wsjc.manager.service.routine.region.WjRegionService;
import com.wsjc.manager.service.routine.user.WjUserService;

/**
 * <b>功能说明:
 * TODO... 无注释
 * 
 */
@Service("pushPersist")
public class PushPersist {

	private static Logger logger = LoggerFactory.getLogger(PushPersist.class);

    @Autowired
    private WjDataLogService wjDataLogService;

	@Autowired
	private WjPushService wjPushService;
	
	@Autowired
	private WjRegionService wjRegionService;
	
	@Autowired
	private WjUserService wjUserService;
	
	@Bean
	public SystemWebSocketHandler systemWebSocketHandler() {
		return new SystemWebSocketHandler();
	}
	
	
	
    /**
     * 更新地图更新状态.<br/>
     * @param id
     * @param status
     */
    public void updateDataLog(WjDataLog wjDataLog, String pushStatus) {
    	wjDataLog.setPushStatus(pushStatus);
    	wjDataLogService.updateData(wjDataLog);
    }


    /**
     * 从数据库中取一次数据用来当系统启动时初始化
     */
    public void initPushDataLogFromDB() throws InterruptedException{
    	
    	logger.info("===>init get push data log from database");

        // 组装查询条件，通知状态不成功，并且还没有超过最大通知次数的
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("pushStatus", CommonConst.DATA_STATUS_CREATE); // 创建状态

        List<WjDataLog> dataLogList = wjDataLogService.listBy(paramMap);
        if (dataLogList == null || dataLogList.isEmpty()) {
        	logger.info("app-push|initPushDataLogFromDB| the dataLogList is null or empty..");
            return;
        }

        for (WjDataLog wjDataLog : dataLogList) {
				App.tasks.put(new PushTask(wjDataLog)); // 添加到通知队列(第一次通知)
        }
        logger.info("app-push|initPushDataLogFromDB| init is successful, size: {}", dataLogList.size());
    }


    /**
     * 推送消息
     * @param dataId
     * @param dataType
     * @param hospitalId
     */
	public void pushMsg(String logId, String detectionResult, String dataId, String dataType, String hospitalId, String hospitalName, String detectionTime, String smsMsg) throws Exception{
		
		WjDataLog wjDataLog = wjDataLogService.getDataById(logId);
		if(wjDataLog.getPushStatus().equals(CommonConst.DATA_STATUS_SUCCESS)){
			return ;
		}
		/**
		 * 插入推送表
		 * 不合格数据发送sms
		 */
		String areaId = hospitalId.substring(5, 11);
		wjPushService.pushMsg(detectionResult, hospitalId, dataType, areaId, smsMsg, detectionTime);
		
		/** 构建相应数据 **/
		SocketRespVo respVo = new SocketRespVo();
		
		respVo.setDataType(dataType);
		respVo.setDetectionResult(detectionResult);
		respVo.setHospitalName(hospitalName);
		respVo.setHospitalId(hospitalId);
		respVo.setDetectionTime(detectionTime);
		
        ApiCommonResultVo apiCommonResultVo = new ApiCommonResultVo(0, "处理成功..", respVo) ;
		String respMsg = JSON.toJSONString(apiCommonResultVo);
		
		/** 获取推送用户 **/
		List<WjUser> users = wjUserService.queryUsersByScope(areaId);
		Set<String> usernames = Sets.newHashSet();
		for(WjUser user: users){
			usernames.add(user.getUsername());
		}
		
		/**  * 新数据webSocket到页面     ***/
		systemWebSocketHandler().sendMessageToUser(usernames, new TextMessage(respMsg));
		
	}


}
